import sys
import tkinter as tk
from tkinter import messagebox
from tkcalendar import DateEntry
from datetime import datetime, timedelta
import requests
import json

# 定义计算校验和的函数（仅计算关键时间字段和机器码，按固定顺序）
def calculate_checksum(data):
    # 按后端预期顺序拼接关键时间字段和机器码
    combined_str = (
        data["data"]["query_time_start"] +
        data["data"]["query_time_end"] +
        data["data"]["time"] +
        data["machine_id"]
    )
    ascii_sum = sum(ord(c) for c in combined_str)
    return str(ascii_sum % 100)

def query_data():
    # 获取日期选择器的值并格式化为指定字符串
    start_date = date_start.get_date()
    end_date = date_end.get_date()
    
    # 获取时间选择器的值并验证数字有效性
    try:
        start_hour = int(spin_start_hour.get())
        start_minute = int(spin_start_minute.get())
        end_hour = int(spin_end_hour.get())
        end_minute = int(spin_end_minute.get())
    except ValueError:
        messagebox.showerror("输入错误", "小时/分钟必须为有效数字")
        return

    # 简单验证日期是否选择
    if not start_date or not end_date:
        messagebox.showerror("输入错误", "请选择开始和结束日期")
        return

    try:
        # 构造完整的时间字符串（格式严格匹配后端解析规则）
        start_datetime = datetime(
            year=start_date.year,
            month=start_date.month,
            day=start_date.day,
            hour=start_hour,
            minute=start_minute,
            second=0
        )
        
        end_datetime = datetime(
            year=end_date.year,
            month=end_date.month,
            day=end_date.day,
            hour=end_hour,
            minute=end_minute,
            second=0
        )

        # 验证开始时间不能晚于结束时间
        if start_datetime > end_datetime:
            messagebox.showerror("时间错误", "开始时间不能晚于结束时间")
            return

    except Exception as e:
        messagebox.showerror("格式错误", f"时间格式不正确: {str(e)}")
        return

    # 构造发送数据（使用本地时间，与后端保持一致）
    data = {
        "data": {
            "query_time_start": start_datetime.strftime('%Y%m%d%H%M%S'),
            "query_time_end": end_datetime.strftime('%Y%m%d%H%M%S'),
            "time": datetime.now().strftime('%Y%m%d%H%M%S'),
        },
        "machine_id": machine_id
    }

    # 计算校验和（仅包含关键时间字段和机器码）
    data["data"]["check_sum"] = calculate_checksum(data)

    # 打印发送数据用于调试
    print("发送的JSON数据:", json.dumps(data, indent=2))

    # 发送POST请求
    try:
        response = requests.post(
            'http://47.108.221.119:5000/query',
            json=data,
            timeout=10  # 设置超时时间
        )
        
        response.raise_for_status()  # 抛出HTTP错误
        result = response.json()
        
        if result.get("code") == "0":
            messagebox.showinfo("成功", "数据查询成功")
            result_text.delete(1.0, tk.END)
            result_text.insert(tk.END, json.dumps(result, indent=4))
        else:
            messagebox.showerror("错误", f"服务器返回错误: {result.get('message', '未知错误')}")
    
    except requests.exceptions.RequestException as e:
        messagebox.showerror("网络错误", f"请求失败: {str(e)}")
    except json.JSONDecodeError:
        messagebox.showerror("格式错误", f"服务器返回非JSON数据: {response.text[:200]}")


# 获取机器码（支持默认值）
machine_id = sys.argv[1] if len(sys.argv) > 1 else "未提供机器码"

# 创建主窗口
root = tk.Tk()
root.title("数据查询工具")
root.geometry("600x400")  # 设置窗口大小

# 标题标签
label_title = tk.Label(root, text="数据查询条件", font=("Arial", 16, "bold"))
label_title.pack(pady=15)

# 机器码显示区域
frame_machine_id = tk.Frame(root)
frame_machine_id.pack(pady=10, padx=20, fill=tk.X)

label_machine = tk.Label(frame_machine_id, text="当前机器码:", font=("Arial", 12))
label_machine.pack(side=tk.LEFT)

label_machine_value = tk.Label(frame_machine_id, text=machine_id, font=("Arial", 12, "bold"), fg="blue")
label_machine_value.pack(side=tk.LEFT, padx=10)

# 日期时间选择区域
frame_start = tk.Frame(root, padx=20)
frame_start.pack(pady=5, fill=tk.X)

# 开始日期
label_start_date = tk.Label(frame_start, text="开始日期:", font=("Arial", 12))
label_start_date.pack(side=tk.LEFT, padx=5)

date_start = DateEntry(
    frame_start,
    width=12,
    background='darkblue',
    foreground='white',
    borderwidth=2,
    date_pattern='yyyy/mm/dd',  # 固定日期格式
    font=("Arial", 12)
)
date_start.pack(side=tk.LEFT, padx=5)

# 开始时间
frame_start_time = tk.Frame(frame_start)
frame_start_time.pack(side=tk.LEFT, padx=10)

label_start_time = tk.Label(frame_start_time, text="时间:", font=("Arial", 12))
label_start_time.pack(side=tk.LEFT)

spin_start_hour = tk.Spinbox(
    frame_start_time,
    from_=0,
    to=23,
    format="%02.0f",
    width=4,
    font=("Arial", 12)
)
spin_start_hour.pack(side=tk.LEFT)

label_colon = tk.Label(frame_start_time, text=":", font=("Arial", 12))
label_colon.pack(side=tk.LEFT)

spin_start_minute = tk.Spinbox(
    frame_start_time,
    from_=0,
    to=59,
    format="%02.0f",
    width=4,
    font=("Arial", 12)
)
spin_start_minute.pack(side=tk.LEFT)

# 结束日期
frame_end = tk.Frame(root, padx=20)
frame_end.pack(pady=5, fill=tk.X)

label_end_date = tk.Label(frame_end, text="结束日期:", font=("Arial", 12))
label_end_date.pack(side=tk.LEFT, padx=5)

date_end = DateEntry(
    frame_end,
    width=12,
    background='darkblue',
    foreground='white',
    borderwidth=2,
    date_pattern='yyyy/mm/dd',
    font=("Arial", 12)
)
date_end.pack(side=tk.LEFT, padx=5)

# 结束时间
frame_end_time = tk.Frame(frame_end)
frame_end_time.pack(side=tk.LEFT, padx=10)

label_end_time = tk.Label(frame_end_time, text="时间:", font=("Arial", 12))
label_end_time.pack(side=tk.LEFT)

spin_end_hour = tk.Spinbox(
    frame_end_time,
    from_=0,
    to=23,
    format="%02.0f",
    width=4,
    font=("Arial", 12)
)
spin_end_hour.pack(side=tk.LEFT)

label_colon_end = tk.Label(frame_end_time, text=":", font=("Arial", 12))
label_colon_end.pack(side=tk.LEFT)

spin_end_minute = tk.Spinbox(
    frame_end_time,
    from_=0,
    to=59,
    format="%02.0f",
    width=4,
    font=("Arial", 12)
)
spin_end_minute.pack(side=tk.LEFT)

# 查询按钮
button_query = tk.Button(
    root,
    text="执行查询",
    command=query_data,
    font=("Arial", 12),
    bg="#4CAF50",
    fg="white",
    padx=20,
    pady=5
)
button_query.pack(pady=20)

# 结果显示区域
frame_result = tk.Frame(root, padx=20, pady=10, bd=1, relief=tk.SUNKEN)
frame_result.pack(fill=tk.BOTH, expand=True)

result_text = tk.Text(frame_result, wrap=tk.WORD, font=("Courier New", 10))
result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

scrollbar = tk.Scrollbar(frame_result, command=result_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

result_text.config(yscrollcommand=scrollbar.set)

root.mainloop()
